package com.lagou.edu.interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UrlPathHelper;

import com.lagou.edu.annotation.Securiety;

/**
 * 自定义springmvc拦截器
 */
public class MyIntercepter02 implements HandlerInterceptor {


    /**
     * 会在handler方法业务逻辑执行之前执行
     * 往往在这里完成权限校验工作
     * @param request
     * @param response
     * @param handler
     * @return  返回值boolean代表是否放行，true代表放行，false代表中止
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyIntercepter02 preHandle......");
        Securiety annotation;
		// 访问权限
        if (handler instanceof HandlerMethod) {
			UrlPathHelper urlPathHelper = new UrlPathHelper();
			String urlPath = urlPathHelper.getLookupPathForRequest(request);

			annotation = ((HandlerMethod) handler).getMethodAnnotation(Securiety.class);
		} else {
			return true;
		}
		// 如果有@Securiety注解，则验证访问用户
		if (annotation != null) {
			String[] value = annotation.value();
			if (value.length >0) {
				boolean hasPermission =false;
				String userName = request.getParameter("userName");
				if (null==userName) {
					 response.getWriter().write("no permission");
					 return false;
				}
				for (int i = 0; i < value.length; i++) {
					if (userName.equals(value[i])) {
						hasPermission = true;
						break;
					}
				}
				// 无权限访问提示
				if (!hasPermission) {
					response.getWriter().write("no permission");
					return false;
				}
				
			}
			return true;
		}

        return true;
    }


    /**
     * 会在handler方法业务逻辑执行之后尚未跳转页面时执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView  封装了视图和数据，此时尚未跳转页面呢，你可以在这里针对返回的数据和视图信息进行修改
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyIntercepter02 postHandle......");
    }

    /**
     * 页面已经跳转渲染完毕之后执行
     * @param request
     * @param response
     * @param handler
     * @param ex  可以在这里捕获异常
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyIntercepter02 afterCompletion......");
    }
}
